import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isFunction from "lodash/isFunction";
import _isEmpty from "lodash/isEmpty";
import _kebabCase from "lodash/kebabCase";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _class;

import React from 'react';
import loadScript from 'load-script';
import qs from 'querystring';
import { Modal, Upload, Button, Icon, Spin } from 'antd';
import { Bind } from 'lodash-decorators';
import isAbsoluteUrl from 'is-absolute-url';
import intl from "../../utils/intl";
import request from "../../utils/request";
import { getEnvConfig } from "../../utils/iocUtils";
import notification from "../../utils/notification";
import { getCurrentLanguage, getAttachmentUrl, getAccessToken, isTenantRoleLevel, getCurrentOrganizationId } from "../../utils/utils"; // import './style.less';

var promise;

function getEditorNamespace(editorURL) {
  if (typeof editorURL !== 'string' || editorURL.length < 1) {
    throw new TypeError('CKEditor URL must be a non-empty string.');
  }

  if ('CKEDITOR' in window) {
    if (window.CKEDITOR) {
      window.CKEDITOR.disableAutoInline = true;
    }

    return Promise.resolve(window.CKEDITOR);
  }

  if (!promise) {
    promise = new Promise(function (scriptResolve, scriptReject) {
      loadScript(editorURL, function (err) {
        if (err) {
          scriptReject(err);
        } else {
          if (window.CKEDITOR) {
            window.CKEDITOR.disableAutoInline = true;
          }

          scriptResolve(window.CKEDITOR);
          promise = undefined;
        }
      });
    });
  }

  return promise;
}

function checkApiTenantPrefix() {
  var organizationId = getCurrentOrganizationId();
  return isTenantRoleLevel() ? "/".concat(organizationId) : '';
}

var CKEditor = (_dec = Bind(), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), (_class = /*#__PURE__*/function (_React$Component) {
  _inherits(CKEditor, _React$Component);

  var _super = _createSuper(CKEditor);

  function CKEditor(props) {
    var _this;

    _classCallCheck(this, CKEditor);

    _this = _super.call(this, props);
    _this.element = null;
    _this.editor = null;
    _this.state = {
      fileUploadModalVisible: false,
      file: null
    };
    _this.config = getEnvConfig();
    return _this;
  }

  _createClass(CKEditor, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.initCKEditor();
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this._destroyEditor();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var props = this.props,
          editor = this.editor;
      /* istanbul ignore next */

      if (!editor) {
        return;
      }

      if (prevProps.data !== props.data && editor.getData() !== props.data) {
        var newContent = props.data; // if(props.privateBucket){
        //   const accessToken = getAccessToken();
        //   const organizationId = getCurrentOrganizationId();
        //   const { CPAAS_FILE } = this.config;
        //           const imgReg = new RegExp(/<img\b.*?(?:>|\/>)/g);
        //            newContent = props.data.replace(imgReg, (item) => {
        //             const url = item.match(
        //               /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\\.,@?^=%&:/~\\+#]*[\w\-\\@?^=%&/~\\+#])+([\S]+[.]*[\w\-\\@?^=%&/~\\+#])/
        //             )
        //               ? props.data.match(
        //                   /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\\.,@?^=%&:/~\\+#]*[\w\-\\@?^=%&/~\\+#])+([\S]+[.]*[\w\-\\@?^=%&/~\\+#])/
        //                 )[0]
        //               : undefined;
        //             const newUrl = url.startsWith(CPAAS_FILE)?url:`${CPAAS_FILE}/v1/${organizationId}/files/redirect-url?bucketName=${props.bucketName}&access_token=${accessToken}&url=${encodeURIComponent(
        //               url
        //             )}`;
        //             let replaceImg = item;
        //             replaceImg = item.replace(
        //               /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\\.,@?^=%&:/~\\+#]*[\w\-\\@?^=%&/~\\+#])+([\S]+[.]*[\w\-\\@?^=%&/~\\+#])/,
        //               newUrl
        //             );
        //             return replaceImg;
        //           });
        // }

        editor.setData(newContent);
      }

      if (prevProps.readOnly !== props.readOnly) {
        editor.setReadOnly(props.readOnly);
      }

      if (prevProps.style !== props.style) {
        editor.container.setStyles(props.style);
      }

      this._attachEventHandlers(prevProps);

      window.addEventListener('popstate', function () {
        // to do
        if (editor && editor.commands.maximize.state === 1) {
          editor.destroy();
          window.location.reload();
        }
      });
    }
  }, {
    key: "getContent",
    value: function getContent() {
      var _this$props$privateBu = this.props.privateBucket,
          privateBucket = _this$props$privateBu === void 0 ? false : _this$props$privateBu;
      var CPAAS_FILE = this.config.CPAAS_FILE;
      var content = this.editor.getData();
      var str = content;

      if (privateBucket) {
        var imgReg = new RegExp(/<img\b.*?(?:>|\/>)/g);
        str = content.replace(imgReg, function (item) {
          var replaceImg = item.replace(/(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\\.,@?^=%&:/~\\+#]*[\w\-\\@?^=%&/~\\+#])+([\S]+[.]*[\w\-\\@?^=%&/~\\+#])/, function (temp) {
            var _qs$parse = qs.parse(temp.substring(temp.indexOf('?') + 1), '&amp;'),
                url = _qs$parse.url;

            return temp.startsWith(CPAAS_FILE) ? url || temp : temp;
          });
          return replaceImg;
        });
      }

      return str;
    }
  }, {
    key: "initCKEditor",
    value: function initCKEditor() {
      var _this2 = this;

      var _this$props = this.props,
          _this$props$onEditorC = _this$props.onEditorChange,
          onEditorChange = _this$props$onEditorC === void 0 ? function () {} : _this$props$onEditorC,
          content = _this$props.content,
          readOnly = _this$props.readOnly,
          _this$props$config = _this$props.config,
          config = _this$props$config === void 0 ? {} : _this$props$config,
          style = _this$props.style;
      var editorLoading = this.state.editorLoading;

      if (!editorLoading && !window.CKEDITOR) {
        this.setState({
          editorLoading: true
        });
      }

      getEditorNamespace(CKEditor.editorUrl).then(function (CKEDITOR) {
        var _this2$config = _this2.config,
            CPAAS_FILE = _this2$config.CPAAS_FILE,
            BKT_PUBLIC = _this2$config.BKT_PUBLIC;
        var _this2$props = _this2.props,
            _this2$props$bucketNa = _this2$props.bucketName,
            bucketName = _this2$props$bucketNa === void 0 ? BKT_PUBLIC : _this2$props$bucketNa,
            _this2$props$privateB = _this2$props.privateBucket,
            privateBucket = _this2$props$privateB === void 0 ? false : _this2$props$privateB;
        var organizationId = getCurrentOrganizationId(); // eslint-disable-next-line no-useless-catch

        try {
          var language = _kebabCase(getCurrentLanguage() || 'zh_cn').toLocaleLowerCase();

          _this2.setState({
            editorLoading: false
          });

          if (_this2.element) {
            _this2.editor = CKEDITOR.replace(_this2.element, _objectSpread({
              // extraPlugins:
              //   'image2',
              // codeSnippet_theme: 'solarized_dark',
              // customConfig: '/lib/ckeditor/config.js',
              removeButtons: 'About,Flash,Save,Source,Form,Checkbox,Button,ShowBlocks,NewPage,Print,Language,Templates,CreateDiv,Radio,TextField,Textarea,Select,HiddenField',
              removePlugins: 'image,scayt,wsc,iframe',
              language: language,
              readOnly: readOnly,
              height: 600,
              uploadUrl: "".concat(CPAAS_FILE, "/v1").concat(checkApiTenantPrefix(), "/files/multipart"),
              filebrowserUploadUrl: "".concat(CPAAS_FILE, "/v1").concat(checkApiTenantPrefix(), "/files/multipart"),
              disableNativeSpellChecker: false,
              font_names: "Arial/Arial, Helvetica, sans-serif; Comic Sans MS/Comic Sans MS;Courier New/Courier New;Georgia/Georgia;Lucida Sans Unicode/Lucida Sans Unicode;Times New Roman/Times New Roman, Times, serif;Verdana;\u5B8B\u4F53/\u5B8B\u4F53;\u9ED1\u4F53/\u9ED1\u4F53;\u4EFF\u5B8B/\u4EFF\u5B8B_GB2312;\u6977\u4F53/\u6977\u4F53_GB2312;\u96B6\u4E66/\u96B6\u4E66;\u5E7C\u5706/\u5E7C\u5706;\u5FAE\u8F6F\u96C5\u9ED1/\u5FAE\u8F6F\u96C5\u9ED1;"
            }, config));
          }

          if (_this2.editor) {
            _this2.editor.filter = _this2.editor.filter || {};

            _this2._attachEventHandlers();

            if (content) {
              if (privateBucket) {
                var accessToken = getAccessToken();
                var imgReg = new RegExp(/<img\b.*?(?:>|\/>)/g);
                var newContent = content.replace(imgReg, function (item) {
                  var url = item.match(/(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\\.,@?^=%&:/~\\+#]*[\w\-\\@?^=%&/~\\+#])+([\S]+[.]*[\w\-\\@?^=%&/~\\+#])/) ? content.match(/(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\\.,@?^=%&:/~\\+#]*[\w\-\\@?^=%&/~\\+#])+([\S]+[.]*[\w\-\\@?^=%&/~\\+#])/)[0] : undefined;
                  var newUrl = "".concat(CPAAS_FILE, "/v1/").concat(organizationId, "/files/redirect-url?bucketName=").concat(bucketName, "&access_token=").concat(accessToken, "&url=").concat(encodeURIComponent(url));
                  var replaceImg = item;
                  replaceImg = item.replace(/(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\\.,@?^=%&:/~\\+#]*[\w\-\\@?^=%&/~\\+#])+([\S]+[.]*[\w\-\\@?^=%&/~\\+#])/, newUrl);
                  return replaceImg;
                });

                _this2.editor.setData(newContent);
              } else {
                _this2.editor.setData(content);
              }
            }

            _this2._attachEventHandlers();

            if (_isFunction(_this2.editor.on)) {
              _this2.editor.on('change', function (evt) {
                // getData() returns CKEditor's HTML content.
                onEditorChange(evt.editor.getData());
              });

              if (style) {
                _this2.editor.on('loaded', function () {
                  _this2.editor.container.setStyles(style);

                  _this2.editor.addCommand('insertFiles', {
                    exec: function exec() {
                      // const now = new Date();
                      // editor.insertHtml( `The current date and time is: <em>${ now.toString() }</em>` );
                      _this2.setState({
                        fileUploadModalVisible: true
                      });
                    }
                  });

                  _this2.editor.ui.addButton('insertFilesBtn', {
                    label: intl.get('cpaas.common.richTextEditor.insertFile').d('插入文件'),
                    command: 'insertFiles',
                    toolbar: 'insert',
                    icon: 'Templates'
                  });
                });
              }

              var _accessToken = getAccessToken();

              _this2.editor.on('fileUploadRequest', function (evt) {
                var _this2$props$bucketDi = _this2.props.bucketDirectory,
                    bucketDirectory = _this2$props$bucketDi === void 0 ? 'editor' : _this2$props$bucketDi;
                var fileLoader = evt.data.fileLoader;
                var xhr = fileLoader.xhr;
                xhr.open('POST', fileLoader.uploadUrl, true);

                if (_accessToken) {
                  xhr.setRequestHeader('Authorization', "bearer ".concat(_accessToken));
                }

                xhr.setRequestHeader('Cache-Control', 'no-cache');
                xhr.setRequestHeader('X-File-Name', _this2.fileName);
                xhr.setRequestHeader('X-File-Size', _this2.total);
                var formData = new FormData();
                formData.append('file', fileLoader.file, fileLoader.fileName);
                formData.append('bucketName', bucketName);
                formData.append('directory', bucketDirectory);
                formData.append('fileName', fileLoader.fileName);
                xhr.send(formData);
                evt.stop();
              }, null, null, 4);

              _this2.editor.on('fileUploadResponse', function (evt) {
                // Prevent the default response handler.
                evt.stop(); // FIXME: @LiJun

                var _this2$props$resolveI = _this2.props.resolveImageUrl,
                    resolveImageUrl = _this2$props$resolveI === void 0 ? function () {} : _this2$props$resolveI;
                var fileLoader = evt.data.fileLoader;
                var xhr = fileLoader.xhr;
                var res = xhr.responseText;

                if (isAbsoluteUrl(res)) {
                  // const organizationId = getCurrentOrganizationId();
                  // const params = qs.stringify({
                  //   url: res,
                  //   bucketName,
                  //   access_token: accessToken,
                  // });
                  // const imageUrl = `${CPAAS_FILE}/v1/${organizationId}/files/redirect-url?${params}`;
                  var imageUrl = resolveImageUrl(res, bucketName);
                  var newUrl = res;

                  if (privateBucket) {
                    newUrl = "".concat(CPAAS_FILE, "/v1/").concat(organizationId, "/files/redirect-url?bucketName=").concat(bucketName, "&access_token=").concat(_accessToken, "&url=").concat(encodeURIComponent(res));
                  } // eslint-disable-next-line no-param-reassign


                  evt.data.url = imageUrl && isAbsoluteUrl(imageUrl) ? imageUrl : newUrl;
                } else {
                  // eslint-disable-next-line no-param-reassign
                  evt.data.message = JSON.parse(res).message;
                } // Get XHR and response.

              });
            }
          }
        } catch (e) {
          throw e;
        }
      }).catch(window.console.error); // getEditorNamespace(CKEditor.editorUrl)
      //   .then(CKEDITOR => {
      //     // const constructor = this.props.type === 'inline' ? 'inline' : 'replace';
      //     this.setState({
      //       editorLoading: false,
      //     });
      //     const language = kebabCase(getCurrentLanguage() || 'zh_cn').toLocaleLowerCase();
      //     this.editor = CKEDITOR.replace(this.element, {
      //       editorName: 'richTextEditor',
      //       language,
      //       // customConfig: '',
      //       // Define the toolbar: https://ckeditor.com/docs/ckeditor4/latest/guide/dev_toolbar
      //       // The full preset from CDN which we used as a base provides more features than we need.
      //       // Also by default it comes with a 3-line toolbar. Here we put all buttons in two rows.
      //       // toolbar: [{
      //       //     name: 'clipboard',
      //       //     items: ['PasteFromWord', '-', 'Undo', 'Redo'],
      //       //   },
      //       //   {
      //       //     name: 'basicstyles',
      //       //     items: ['Bold', 'Italic', 'Underline', 'Strike', 'RemoveFormat', 'Subscript', 'Superscript'],
      //       //   },
      //       //   {
      //       //     name: 'links',
      //       //     items: ['Link', 'Unlink'],
      //       //   },
      //       //   {
      //       //     name: 'paragraph',
      //       //     items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote'],
      //       //   },
      //       //   {
      //       //     name: 'insert',
      //       //     items: ['Image', 'Table'],
      //       //   },
      //       //   {
      //       //     name: 'editing',
      //       //     items: ['Scayt'],
      //       //   },
      //       //   '/',
      //       //   {
      //       //     name: 'styles',
      //       //     items: ['Format', 'Font', 'FontSize'],
      //       //   },
      //       //   {
      //       //     name: 'colors',
      //       //     items: ['TextColor', 'BGColor', 'CopyFormatting'],
      //       //   },
      //       //   {
      //       //     name: 'align',
      //       //     items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
      //       //   },
      //       //   {
      //       //     name: 'document',
      //       //     items: ['Print', 'Source', 'NewPage'],
      //       //   },
      //       // ],
      //       // Since we define all configuration options here, let's instruct CKEditor to not load config.js which it does by default.
      //       // One HTTP request less will result in a faster startup time.
      //       // For more information check https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-customConfig
      //       // // Upload images to a CKFinder connector (note that the response type is set to JSON).
      //       // uploadUrl: '/apps/ckfinder/3.4.5/core/connector/php/connector.php?command=QuickUpload&type=Files&responseType=json',
      //       // Configure your file manager integration. This example uses CKFinder 3 for PHP.
      //       // filebrowserBrowseUrl: '/apps/ckfinder/3.4.5/ckfinder.html',
      //       // filebrowserImageBrowseUrl: '/apps/ckfinder/3.4.5/ckfinder.html?type=Images',
      //       // filebrowserUploadUrl: '/apps/ckfinder/3.4.5/core/connector/php/connector.php?command=QuickUpload&type=Files',
      //       // filebrowserImageUploadUrl: '/apps/ckfinder/3.4.5/core/connector/php/connector.php?command=QuickUpload&type=Images',
      //       // Sometimes applications that convert HTML to PDF prefer setting image width through attributes instead of CSS styles.
      //       // For more information check:
      //       //  - About Advanced Content Filter: https://ckeditor.com/docs/ckeditor4/latest/guide/dev_advanced_content_filter
      //       //  - About Disallowed Content: https://ckeditor.com/docs/ckeditor4/latest/guide/dev_disallowed_content
      //       //  - About Allowed Content: https://ckeditor.com/docs/ckeditor4/latest/guide/dev_allowed_content_rules
      //       disallowedContent: 'img{width,height,float}',
      //       extraAllowedContent: 'img[width,height,align];span{background}',
      //       // Enabling extra plugins, available in the full-all preset: https://ckeditor.com/cke4/presets
      //       extraPlugins:
      //         'colorbutton,font,justify,print,image2,codesnippet,placeholder,preview,bidi,emoji,find,selectall,copyformatting,newpage,uploadimage',
      //       codeSnippet_theme: 'solarized_dark',
      //       /** ********************* File management support ********************** */
      //       // In order to turn on support for file uploads, CKEditor has to be configured to use some server side
      //       // solution with file upload/management capabilities, like for example CKFinder.
      //       // For more information see https://ckeditor.com/docs/ckeditor4/latest/guide/dev_ckfinder_integration
      //       // Uncomment and correct these lines after you setup your local CKFinder instance.
      //       // filebrowserBrowseUrl: 'http://example.com/ckfinder/ckfinder.html',
      //       // filebrowserUploadUrl: 'http://example.com/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
      //       /** ********************* File management support ********************** */
      //       // Make the editing area bigger than default.
      //       height: 600,
      //       readOnly,
      //       // An array of stylesheets to style the WYSIWYG area.
      //       // Note: it is recommended to keep your own styles in a separate file in order to make future updates painless.
      //       // contentsCss: [
      //       //   // 'http://cdn.ckeditor.com/4.11.4/full-all/contents.css',
      //       //   'assets/css/pastefromword.css',
      //       // ],
      //       // This is optional, but will let us define multiple different styles for multiple editors using the same CSS file.
      //       bodyClass: 'document-editor',
      //       // Reduce the list of block elements listed in the Format dropdown to the most commonly used.
      //       format_tags: 'p;h1;h2;h3;pre',
      //       // Simplify the Image and Link dialog windows. The "Advanced" tab is not needed in most cases.
      //       removeDialogTabs: 'image:advanced;link:advanced',
      //       removeButtons: 'About',
      //       removePlugins: 'image',
      //       uploadUrl: `${CPAAS_FILE}/v1/files/multipart`,
      //       filebrowserUploadUrl: `${CPAAS_FILE}/v1/files/multipart`,
      //       // Define the list of styles which should be available in the Styles dropdown list.
      //       // If the "class" attribute is used to style an element, make sure to define the style for the class in "mystyles.css"
      //       // (and on your website so that it rendered in the same way).
      //       // Note: by default CKEditor looks for styles.js file. Defining stylesSet inline (as below) stops CKEditor from loading
      //       // that file, which means one HTTP request less (and a faster startup).
      //       // For more information see https://ckeditor.com/docs/ckeditor4/latest/guide/dev_styles
      //       stylesSet: [
      //         /* Inline Styles */
      //         {
      //           name: 'Marker',
      //           element: 'span',
      //           attributes: {
      //             class: 'marker',
      //           },
      //         },
      //         {
      //           name: 'Cited Work',
      //           element: 'cite',
      //         },
      //         {
      //           name: 'Inline Quotation',
      //           element: 'q',
      //         },
      //         /* Object Styles */
      //         {
      //           name: 'Special Container',
      //           element: 'div',
      //           styles: {
      //             padding: '5px 10px',
      //             background: '#eee',
      //             border: '1px solid #ccc',
      //           },
      //         },
      //         {
      //           name: 'Compact table',
      //           element: 'table',
      //           attributes: {
      //             cellpadding: '5',
      //             cellspacing: '0',
      //             border: '1',
      //             bordercolor: '#ccc',
      //           },
      //           styles: {
      //             'border-collapse': 'collapse',
      //           },
      //         },
      //         {
      //           name: 'Borderless Table',
      //           element: 'table',
      //           styles: {
      //             'border-style': 'hidden',
      //             'background-color': '#E6E6FA',
      //           },
      //         },
      //         {
      //           name: 'Square Bulleted List',
      //           element: 'ul',
      //           styles: {
      //             'list-style-type': 'square',
      //           },
      //         },
      //       ],
      //       ...config,
      //     });
      //     // CKEDITOR.plugins.add( 'customUploadFiles', {
      //     //   icons: 'templates',
      //     //   init: _editor => {
      //     //     _editor.addCommand( 'insertFiles', {
      //     //       exec: () => {
      //     //         // const now = new Date();
      //     //         // editor.insertHtml( `The current date and time is: <em>${ now.toString() }</em>` );
      //     //         this.setState({
      //     //           fileUploadModalVisible: true,
      //     //         });
      //     //       },
      //     //     });
      //     //     _editor.ui.addButton( 'insertFilesBtn', {
      //     //         label: intl.get('cpaas.common.richTextEditor.insertFile').d('插入文件'),
      //     //         command: 'insertFiles',
      //     //         toolbar: 'insert',
      //     //         icon: 'Templates',
      //     //     });
      //     //   },
      //     // });
      //     const { editor } = this;
      //     if (editor) {
      //       // editor.addCommand('insertFiles', {
      //       //   exec: () => {
      //       //     // const now = new Date();
      //       //     // editor.insertHtml( `The current date and time is: <em>${ now.toString() }</em>` );
      //       //     this.setState({
      //       //       fileUploadModalVisible: true,
      //       //     });
      //       //   },
      //       // });
      //       // editor.ui.addButton('insertFilesBtn', {
      //       //   label: intl.get('cpaas.common.richTextEditor.insertFile').d('插入文件'),
      //       //   command: 'insertFiles',
      //       //   toolbar: 'insert',
      //       //   icon: 'Templates',
      //       // });
      //       editor.on(
      //         'fileUploadRequest',
      //         evt => {
      //           const { bucketName = 'static-text' } = this.props;
      //           const { fileLoader } = evt.data;
      //           const { xhr } = fileLoader;
      //           const accessToken = getAccessToken();
      //           xhr.open('POST', fileLoader.uploadUrl, true);
      //           if (accessToken) {
      //             xhr.setRequestHeader('Authorization', `bearer ${accessToken}`);
      //           }
      //           xhr.setRequestHeader('Cache-Control', 'no-cache');
      //           xhr.setRequestHeader('X-File-Name', this.fileName);
      //           xhr.setRequestHeader('X-File-Size', this.total);
      //           const formData = new FormData();
      //           formData.append('file', fileLoader.file, fileLoader.fileName);
      //           formData.append('bucketName', bucketName);
      //           formData.append('fileName', fileLoader.fileName);
      //           xhr.send(formData);
      //           evt.stop();
      //         },
      //         null,
      //         null,
      //         4
      //       );
      //       editor.on('fileUploadResponse', evt => {
      //         // Prevent the default response handler.
      //         evt.stop();
      //         const { bucketName = 'static-text' } = this.props;
      //         const { fileLoader } = evt.data;
      //         const { xhr } = fileLoader;
      //         const res = xhr.responseText;
      //         if (isAbsoluteUrl(res)) {
      //           // eslint-disable-next-line no-param-reassign
      //           evt.data.url = getAttachmentUrl(res, bucketName);
      //         } else {
      //           // eslint-disable-next-line no-param-reassign
      //           evt.data.message = JSON.parse(res).message;
      //         }
      //         // Get XHR and response.
      //       });
      //       this._attachEventHandlers();
      //       // if ( this.props.style && this.props.type !== 'inline' ) {
      //       // 	editor.on( 'loaded', () => {
      //       // 		editor.container.setStyles( this.props.style );
      //       // 	} );
      //       // }
      //       if (content) {
      //         editor.setData(content);
      //       }
      //       editor.on('change', evt => {
      //         // getData() returns CKEditor's HTML content.
      //         onChange(evt.editor.getData());
      //       });
      //     }
      //   })
      //   .catch(window.console.error);
    }
  }, {
    key: "_attachEventHandlers",
    value: function _attachEventHandlers() {
      var _this3 = this;

      var prevProps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var props = this.props;
      Object.keys(this.props).forEach(function (propName) {
        if (!propName.startsWith('on') || prevProps[propName] === props[propName]) {
          return;
        }

        _this3._attachEventHandler(propName, prevProps[propName]);
      });
    }
  }, {
    key: "_attachEventHandler",
    value: function _attachEventHandler(propName, prevHandler) {
      // eslint-disable-next-line no-useless-catch
      try {
        var evtName = "".concat(propName[2].toLowerCase()).concat(propName.substr(3));

        if (prevHandler) {
          this.editor.removeListener(evtName, prevHandler);
        }

        if (_isFunction(this.editor.on)) {
          this.editor.on(evtName, this.props[propName]);
        }
      } catch (e) {
        throw e;
      }
    }
  }, {
    key: "_destroyEditor",
    value: function _destroyEditor() {
      // eslint-disable-next-line no-useless-catch
      try {
        if (this.editor) {
          this.editor.destroy(true);
        }

        this.editor = null;
        this.element = null;
      } catch (e) {
        throw e;
      }
    }
  }, {
    key: "beforeUpload",
    value: function beforeUpload(file) {
      this.setState({
        file: file
      });
      return false;
    }
  }, {
    key: "onRemove",
    value: function onRemove() {
      this.setState({
        file: null
      });
    }
  }, {
    key: "upload",
    value: function upload() {
      var _this4 = this;

      var _this$config = this.config,
          CPAAS_FILE = _this$config.CPAAS_FILE,
          BKT_PUBLIC = _this$config.BKT_PUBLIC;
      var _this$props2 = this.props,
          _this$props2$bucketNa = _this$props2.bucketName,
          bucketName = _this$props2$bucketNa === void 0 ? BKT_PUBLIC : _this$props2$bucketNa,
          _this$props2$bucketDi = _this$props2.bucketDirectory,
          bucketDirectory = _this$props2$bucketDi === void 0 ? 'editor' : _this$props2$bucketDi;
      var file = this.state.file;
      var formData = new FormData();
      formData.append('file', file, file.name);
      formData.append('bucketName', bucketName);
      formData.append('directory', bucketDirectory);
      formData.append('fileName', file.name);
      this.setState({
        uploading: true
      });
      request("".concat(CPAAS_FILE, "/v1").concat(checkApiTenantPrefix(), "/files/multipart"), {
        processData: false,
        method: 'POST',
        type: 'FORM',
        body: formData,
        responseType: 'text'
      }).then(function (res) {
        if (isAbsoluteUrl(res)) {
          // success(getAttachmentUrl(res, bucketName));
          _this4.setState({
            uploading: false,
            url: getAttachmentUrl(res, bucketName, undefined, bucketDirectory)
          });

          notification.success();
        } else {
          // failure(JSON.parse(res).message);
          notification.error({
            message: JSON.parse(res).message
          });

          _this4.setState({
            uploading: false
          });
        }
      });
    }
  }, {
    key: "closeFileUploadModal",
    value: function closeFileUploadModal() {
      this.setState({
        fileUploadModalVisible: false,
        uploading: false,
        file: null,
        url: null
      });
    }
  }, {
    key: "onFileUploadModalOk",
    value: function onFileUploadModalOk() {
      var _this$state = this.state,
          url = _this$state.url,
          file = _this$state.file; // eslint-disable-next-line no-useless-catch

      try {
        if (!_isEmpty(url)) {
          this.editor.insertHtml("<a href=\"".concat(url, "\" >").concat(file.name, "</a>"));
        }
      } catch (e) {
        throw e;
      }

      this.setState({
        fileUploadModalVisible: false,
        file: null,
        url: null
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this5 = this;

      var _this$props$style = this.props.style,
          style = _this$props$style === void 0 ? {} : _this$props$style;
      var _this$state2 = this.state,
          uploading = _this$state2.uploading,
          file = _this$state2.file,
          editorLoading = _this$state2.editorLoading,
          fileUploadModalVisible = _this$state2.fileUploadModalVisible;
      var fileUploadProps = {
        beforeUpload: this.beforeUpload,
        fileList: file ? [file] : [],
        onRemove: this.onRemove
      };
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Spin, {
        spinning: editorLoading
      }, /*#__PURE__*/React.createElement("div", {
        contentEditable: "true",
        style: style,
        ref: function ref(_ref) {
          _this5.element = _ref;
        },
        id: "richTextEditor",
        className: "rich-text-editor"
      })), /*#__PURE__*/React.createElement(Modal, {
        title: intl.get('cpaas.common.richTextEditor.insertImage').d('插入文件'),
        visible: fileUploadModalVisible,
        onOk: this.onFileUploadModalOk,
        onCancel: this.closeFileUploadModal
      }, /*#__PURE__*/React.createElement(Upload, fileUploadProps, /*#__PURE__*/React.createElement(Button, null, /*#__PURE__*/React.createElement(Icon, {
        type: "upload"
      }), ' ', intl.get('cpaas.common.richTextEditor.selectFile').d('选择图片'))), /*#__PURE__*/React.createElement("br", null), /*#__PURE__*/React.createElement(Button, {
        className: "upload-demo-start",
        type: "primary",
        onClick: this.upload,
        disabled: _isEmpty(file),
        loading: uploading
      }, uploading ? intl.get('cpaas.common.richTextEditor.uploading').d('正在上传') : intl.get('cpaas.common.richTextEditor.startUpload').d('开始上传'))));
    }
  }]);

  return CKEditor;
}(React.Component), (_applyDecoratedDescriptor(_class.prototype, "getContent", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "getContent"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "initCKEditor", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "initCKEditor"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "_attachEventHandlers", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "_attachEventHandlers"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "_attachEventHandler", [_dec4], Object.getOwnPropertyDescriptor(_class.prototype, "_attachEventHandler"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "_destroyEditor", [_dec5], Object.getOwnPropertyDescriptor(_class.prototype, "_destroyEditor"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "beforeUpload", [_dec6], Object.getOwnPropertyDescriptor(_class.prototype, "beforeUpload"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "onRemove", [_dec7], Object.getOwnPropertyDescriptor(_class.prototype, "onRemove"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "upload", [_dec8], Object.getOwnPropertyDescriptor(_class.prototype, "upload"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "closeFileUploadModal", [_dec9], Object.getOwnPropertyDescriptor(_class.prototype, "closeFileUploadModal"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "onFileUploadModalOk", [_dec10], Object.getOwnPropertyDescriptor(_class.prototype, "onFileUploadModalOk"), _class.prototype)), _class));
export { CKEditor as default };
CKEditor.defaultProps = {
  type: 'classic',
  data: '',
  config: {},
  readOnly: false
};
CKEditor.editorUrl = "".concat((process.env.PUBLIC_URL || '').startsWith('http') || (process.env.PUBLIC_URL || '').startsWith('https') ? process.env.PUBLIC_URL : process.env.BASE_PATH || '/', "lib/ckeditor/ckeditor.js");